package com.chen.base.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

/**
 * @Title:多数据源配置
 * @Description: 第二数据原 test_2
 * @Author: chenjiwei
 * @Date: 2020-10-30 23:00
 * @Version: 1.0.   0
 */
@Configuration
@EnableJpaRepositories(
        basePackages = "com.chen.dao",
        entityManagerFactoryRef = "test2EntityManagerFactory",
        transactionManagerRef = "test2TransactionManager"
)
public class Test2Databaseconfig {

    @Autowired
    @Qualifier("test2DataSource")
    private DataSource dataSource;

    @Autowired
    @Qualifier("test2JpaProperties")
    private JpaProperties test2JpaProperties;

    @Primary
    @Bean(name = "test2EntityManager")
    public EntityManager test2EntityManager(EntityManagerFactoryBuilder builder){
        return test2EntityManagerFactory(builder).getObject().createEntityManager();
    }

    @Primary
    @Bean(name = "test2EntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean test2EntityManagerFactory(EntityManagerFactoryBuilder builder) {
        LocalContainerEntityManagerFactoryBean entityManagerFactory = builder
                .dataSource(dataSource)
                .packages("com.chen.entity")// 配置实体类
                .persistenceUnit("primaryPersistenceUnit")//持久化单元创建一个默认即可，多个便要分别命名
                .properties(test2JpaProperties.getProperties())
                .build();
        return entityManagerFactory;
    }

    @Primary
    @Bean(name = "test2TransactionManager")
    public PlatformTransactionManager test2TransactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(test2EntityManagerFactory(builder).getObject());
    }
}
